package com.codeing.demo.lru;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author shilei
 * @create 2021-08-17 12:57
 * LRU 最近最少使用 算法缓存
 */
public class LruCache<key, value> extends LinkedHashMap<key, value> {

    /**
     * 负载因子
     */
    private static final Float LOAD_FACTOR = 0.75F;

    /**
     * 缓存初始化值
     */
    private Integer initialCapacity;

    /**
     * 构造器
     *
     * @param initialCapacity 初始化缓存长度
     * @param accessOrder     缓存内排序方式
     *                        true-按照访问顺序排序
     *                        false-按照插入顺序排序
     */
    public LruCache(Integer initialCapacity, Boolean accessOrder) {
        super(initialCapacity, LOAD_FACTOR, accessOrder);
        this.initialCapacity = initialCapacity;
    }

    /**
     * 重写父类方法 当缓存达到阈值时删除
     */
    @Override
    protected boolean removeEldestEntry(Map.Entry<key, value> eldest) {
        return super.size() > initialCapacity;
    }
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        LruCache<Object,Object> lruCacheDemo = new LruCache<>(5,false);
        list.forEach(item -> {
            lruCacheDemo.put(item,0);
        });
        lruCacheDemo.put(4,0);
        System.out.println(lruCacheDemo);
        lruCacheDemo.put(5,0);
        System.out.println(lruCacheDemo);
        lruCacheDemo.put(6,0);
        System.out.println(lruCacheDemo);

    }
}
